<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/12
 * Time: 15:56
 */

namespace Kordar\Tree;

class SiblingFinder
{
    private $sibling = [];

    public function __construct($tree, $field, $value, $self = false)
    {
        $this->preSearchSibling($tree, $field, $value, false, $self);
    }

    // 二叉树前序查找某个值的兄弟节点
    private function preSearchSibling($tree, $field, $value, $condition, $self)
    {
        if ($tree === null) {
            return false;
        }

        if ($condition === true) {
            $this->sibling[] = $tree->data;
            $this->preSearchSibling($tree->right, $field, $value, $condition, $self);
            return true;
        }

        if ($tree->data[$field] == $value) {
            if ($self) {
                $this->sibling[] = $tree->data;
            }
            $this->preSearchSibling($tree->right, $field, $value, true, $self);
            return true;
        }

        $this->preSearchSibling($tree->left, $field, $value, $condition, $self);

        if ($this->preSearchSibling($tree->right, $field, $value, $condition, $self)) {
            $this->sibling[] = $tree->data;
            return true;
        }

        return false;
    }

    public function getSibling($col = null)
    {
        return $col !== null ?
            array_column($this->sibling, $col) :
            $this->sibling;
    }

}